import {
  getSysRoleMenusList,
  getSysRolePageList,
  getSysRoleDetail,
  addSysRoleDetail,
  editSysRoleDetail,
  editSysRolePermissions,
  editSysRoleStatus,
  delSysRoleDetail,
  batchDelSysRoleDetail
} from "@/api/system/role";
import { reactive, ref } from "vue";
import { arrayToTree } from "@/utils/truncate";
import $config from "@/config";
import type { PlusPageInstance } from "plus-pro-components";

// 空数据提示（错误提示）
export const tableEmptyText = ref("");
// 页面组件
export const plusPageRef = ref<PlusPageInstance | null>();

// 状态参数
const state = reactive({
  menusCache: [],
  menusCacheInit: false
});

const request = {
  event: {
    /**
     * 列表页面初始化成功时调用
     * 如果开启了 KeepAlive，会在激活后再次调用
     *
     * @param keepAlive 本次调用是否为 keepAlive 激活调用
     * @returns
     */
    onPageShow: async (keepAlive: boolean): Promise<void> => {
      if (keepAlive) {
        plusPageRef.value?.getList();
      }
      await request.get.menusOptions(true);
    }
  },
  get: {
    /**
     * 获取菜单options
     *
     * @param disableCache 是否关闭缓存
     * @returns
     */
    menusOptions: async (disableCache?: boolean) => {
      if (!disableCache && state.menusCacheInit) {
        return state.menusCache;
      }
      const res = (await getSysRoleMenusList()).data;
      const list = arrayToTree(res, {
        transform: item => {
          return {
            value: item[$config.router.routeMenuKey],
            label: item.menuName
          };
        }
      });
      state.menusCache = list;
      state.menusCacheInit = true;
      return list;
    },
    /**
     * 获取分页列表
     *
     * @param params 请求参数
     * @returns
     */
    pageList: async (params: object) => {
      try {
        const res = await getSysRolePageList(params);
        tableEmptyText.value = "资料暂无";
        return {
          data: res.data.list,
          total: res.data.total
        };
      } catch (error) {
        tableEmptyText.value = error.message;
      }
    },
    /**
     * 获取详情
     *
     * @param id 请求ID
     * @returns
     */
    detail: async (id: Id) => {
      return (await getSysRoleDetail(id)).data;
    }
  },
  post: {
    // 新增
    create: async (data: object) => {
      const res = await addSysRoleDetail(data);
      return { id: res.data.id };
    }
  },
  put: {
    // 更新
    update: async (id: Id, data: object) => {
      await editSysRoleDetail(id, data);
    },
    // 提交
    action: async (type: any, id: Id, data: object) => {
      switch (type) {
        case "status":
          // 更新状态
          await editSysRoleStatus(id, data);
          break;
        case "menus":
          // 更新权限
          await editSysRolePermissions(id, data);
          break;
      }
    }
  },
  delete: {
    // 删除（单个）
    remove: async (id: Id) => {
      await delSysRoleDetail(id);
    },
    // 删除（批量）
    batch: async (ids: any) => {
      await batchDelSysRoleDetail({
        ids
      });
    }
  }
};

export default request;
